package com.itfreer.data.syn;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.data.syn.dao.DataSynConfigDao;
import com.itfreer.data.syn.entity.DataSynConfigEntity;
import com.itfreer.form.api.BaseDao;
import com.itfreer.form.api.DictionaryServiceImp;
import com.itfreer.form.api.dictionary.DictionaryEntity;

/**
 * 数据注册服务
 */
@Component
public class DataSynConfigServiceImp extends DictionaryServiceImp<DataSynConfigEntity> implements DataSynConfigService {

	@Autowired
	private DataSynConfigDao dao;

	@Override
	protected BaseDao<DataSynConfigEntity> getDao() {
		return dao;
	}

	@Override
	public String getDictionaryName() {
		return "datasynconfig";
	}

	@Override
	protected DictionaryEntity convert(DataSynConfigEntity entity) {
		DictionaryEntity toEntity = new DictionaryEntity();
		toEntity.setId(entity.getId());
		toEntity.setCode(entity.getTable());
		toEntity.setDisplay(entity.getName());
		toEntity.setAbbreviation(entity.getType());
		toEntity.setInfo(entity.getPara());
		toEntity.setOrder(entity.getOrder());
		toEntity.setValid(true);
		return toEntity;
	}

	@Override
	protected String getDictionaryFields() {
		return "*";
	}

	@Override
	public DictionaryEntity getItem(String id) {
		return dictionaryCache.getDictionary("datasynconfig", id, false);
	}

	@Override
	public List<DictionaryEntity> getItems() {
		return dictionaryCache.getAll("datasynconfig");
	}

	/**
	 * 表是否存在
	 * 
	 * @param table
	 * @return
	 */
	@Override
	public Boolean hasTable(String table) {
		if (table == null || table.equals("")) {
			return false;
		}
		List<DictionaryEntity> items = getItems();
		for (DictionaryEntity item : items) {
			if (table.equals(item.getCode())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取table下所有项
	 * 
	 * @return
	 */
	@Override
	public List<DictionaryEntity> getItems(String table) {
		if (table == null || table.equals("")) {
			return null;
		}
		List<DictionaryEntity> result = new ArrayList<>();
		List<DictionaryEntity> items = getItems();
		for (DictionaryEntity item : items) {
			if (table.equals(item.getCode())) {
				result.add(item);
			}
		}
		result.sort(new Comparator<DictionaryEntity>() {
			@Override
			public int compare(DictionaryEntity o1, DictionaryEntity o2) {
				return o1.getOrder().compareTo(o2.getOrder());
			}
		});
		return result;
	}
}
